package server;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import db.*;

/**
 * Servlet implementation class RegisterServlet
 */
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegisterServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out=response.getWriter();
		String userName="";
		String password="";
		String firstName="";
		String lastName="";
		String regRes="";
		try{
			userName=request.getParameterValues("userName")[0];
		 password=request.getParameterValues("password")[0];
		 firstName=request.getParameterValues("firstName")[0];
		 lastName=request.getParameterValues("lastName")[0];
		
		//PrintWriter out=response.getWriter();
		}catch(Exception e){
			response.sendError(400, "illeagal parameters");
			return;
		}
	try{
			DB db=DBmanager.getDB();
			regRes=db.registerUser(userName, password, firstName, lastName);
			if(regRes.equals("200")){
				request.getSession().setAttribute("userName",userName);
				System.out.println("ok");
				response.setStatus(200);	
			}else{
				System.out.println(regRes);
				out.write(regRes);
				response.setStatus(400);
				//response.sendError(400,regRes);
			}
			DBmanager.getDB().printDB();
		}catch(Exception e){
			e.printStackTrace();
			out.write("we have encountred a technical problem, please register again");
			response.setStatus(400);
			//response.sendError(400, "we have encountred a technical problem, please register again");
			return;
		}	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
}
